import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { ProductGroupTreeC, InputNumberC, RangeDateC, SingleDateC, SelectC } from '../../../../../comps';
import moment from 'moment';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col } from 'antd';
import config from './config';
import dictionaryConfig from '../../../../../utils/dictionaryConfig';
const booleanList = dictionaryConfig.booleanList;
const FormItemLayout = {
  labelCol: {
    xs: { span: 4, offset: 0 },
    sm: { span: 8, offset: 0 },
    md: { span: 8, offset: 0 },
    lg: { span: 8, offset: 0 },
    xl: { span: 10, offset: 0 },
    xxl: { span: 8, offset: 0 },
  },
  wrapperCol: {
    xs: { span: 18, offset: 0 },
    sm: { span: 14, offset: 0 },
    md: { span: 14, offset: 0 },
    lg: { span: 14, offset: 0 },
    xl: { span: 13, offset: 0 },
    xxl: { span: 15, offset: 0 },
  },
};
const benchList = [
  { title: '沪深300', value: '0' },
  { title: '上证50', value: '1' },
  { title: '中证500', value: '2' },
];
@Form.create()
class InitFormC extends PureComponent {
  state = {
    rangedate: [moment().subtract(1, 'years'), moment().subtract(1, 'days')],
    benchmarkList: [], //业绩比较基准下拉
    optimizationGoals: '1', //优化目标默认值
  };

  componentDidMount() {
    this.props.onRef(this);
    if (this.props.typeStatus == '1') {
      //新增状态
      this.setState({
        benchmarkList: [...benchList],
      });
    }
  }

  componentWillUnmount() {}

  typeRender = (item, index) => {
    const {
      type,
      typeStatus,
      globalM: {
        dataDictionary: {
          PORT_OPTIMIZATION_FREQ = [],
          PORT_OPTIMIZATION_OBJECT = [],
          PORT_OPTIMIZATION_COMP_OBJ = [],
          PORT_OPTIMIZATION_BMK = [],
          PORT_OPTIMIZATION_RISK_FREE_RATE = [],
          PORT_OPTIMIZATION_BOND_OBJECT = [],
          PORT_OPTIMIZATION_BOND_COMP_OBJ = [],
        },
      },
    } = this.props;
    const optimize = type == 0 ? PORT_OPTIMIZATION_OBJECT : PORT_OPTIMIZATION_BOND_OBJECT;
    const contrast = type == 0 ? PORT_OPTIMIZATION_COMP_OBJ : PORT_OPTIMIZATION_BOND_COMP_OBJ;
    switch (item.key) {
      case 'portfolio':
        return (
          <Col span={6} key={index}>
            <ProductGroupTreeC
              form={this.props.form}
              dataIndex='portfolio'
              multiple={false}
              formItemLayout={FormItemLayout}
              onChange={this.portfolioChange}
              inveType={'1'}
              disabled={typeStatus == '3'}
            />
          </Col>
        );
      case 'rangeDate':
        return (
          <Col span={6} key={index} className={'dateForm'}>
            <RangeDateC
              initialValue={this.state.rangedate}
              form={this.props.form} // form对象
              title='日期' // 显示名称
              dataIndex={['beginDate', 'endDate']} // Form识别的下拉选项Item ID
              formItemLayout={FormItemLayout}
              required={true}
              message='请选择日期!'
              hasDataED={moment().subtract(1, 'days')}
              onRef={(ref) => {
                this.setState({ RangeDateC: ref });
              }}
              disabled={typeStatus == '3'}
            />
          </Col>
        );
      case 'singleDate':
        return (
          <Col span={6} key={index} className={'dateForm'}>
            <SingleDateC
              form={this.props.form} // form对象
              title='日期' // 显示名称
              dataIndex='beginDate' // Form识别的下拉选项Item ID
              formItemLayout={FormItemLayout}
              required={true}
              message='请选择日期!'
              initialValue={moment()}
            />
          </Col>
        );
      case 'rollBacktest':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='滚动回测' // 显示名称
              dataIndex='rollBacktest' // Form识别的Item ID
              dataSource={[{ value: '0', title: '是' }]}
              initialValue={'0'}
              optionTitle={true}
              formItemLayout={FormItemLayout}
              rules={[{ required: true, message: '请选择滚动回测！' }]}
            />
          </Col>
        );
      case 'freq':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='频率' // 显示名称
              dataIndex='freq' // Form识别的Item ID
              dataSource={PORT_OPTIMIZATION_FREQ.map((item) => {
                return { value: item.code, title: item.value };
              })}
              initialValue={'0'}
              optionTitle={true}
              formItemLayout={FormItemLayout}
              helper={'滚动优化的时间跨度'}
              rules={[{ required: true, message: '请选择频率！' }]}
              disabled={true}
            />
          </Col>
        );
      case 'optimizeObject':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='优化模型' // 显示名称
              dataIndex='optimizeObject' // Form识别的Item ID
              initialValue='1'
              optionTitle={true}
              formItemLayout={FormItemLayout}
              rules={[{ required: true, message: '请选择优化模型！' }]}
              onChange={this.optimizeObjectChange}
              dataSource={config.optimizeObject}
              disabled={typeStatus == '3'}
            />
          </Col>
        );

      case 'expectReturn':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='预期收益率' // 显示名称
              dataIndex='expectReturn' // Form识别的Item ID
              dataSource={booleanList}
              initialValue={'1'}
              onChange={(e) => this.props.handleSelectChange(e, 'expectReturn')}
              optionTitle={true}
              formItemLayout={FormItemLayout}
              helper={'使用对资产的预期收益率作为优化参数'}
              rules={[{ required: true, message: '请选择预期收益率！' }]}
              disabled={typeStatus == '3'}
            />{' '}
          </Col>
        );

      case 'expectVolatility':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='预期波动率' // 显示名称
              dataIndex='expectVolatility' // Form识别的Item ID
              dataSource={[{ value: '1', title: '否' }]}
              initialValue={'1'}
              onChange={(e) => this.props.handleSelectChange(e, 'expectVolatility')}
              optionTitle={true}
              formItemLayout={FormItemLayout}
              helper={'使用对资产的预期波动率作为优化参数，需要上传资产的协方差矩阵'}
              rules={[{ required: true, message: '请选择预期波动率！' }]}
            />{' '}
          </Col>
        );
      case 'optimizationGoals':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='优化目标' // 显示名称
              dataIndex='optimizationGoals' // Form识别的Item ID
              dataSource={config.optimizationGoals}
              initialValue={'1'}
              onChange={this.optimizationGoalsChange}
              optionTitle={true}
              formItemLayout={FormItemLayout}
              rules={[{ required: true, message: '请选最大化效用！' }]}
              disabled={typeStatus == '3'}
            />{' '}
          </Col>
        );

      case 'riskAversion':
        return this.state.optimizationGoals == 1 ? (
          <Col span={6} key={index}>
            <InputNumberC
              form={this.props.form} // form对象
              title='风险厌恶系数' // 显示名称
              dataIndex='riskAversion' // Form识别的Item ID
              initialValue={5}
              min={0}
              max={10}
              step={1}
              formItemLayout={FormItemLayout}
              style={{ width: '100%' }}
              helper={'请输入0-10之间的数字'}
              rules={[{ required: true, message: '请输入风险厌恶系数！' }]}
              disabled={typeStatus == '3'}
            />{' '}
          </Col>
        ) : null;
      case 'contrastConfig':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='对比配置' // 显示名称
              dataIndex='contrastConfig' // Form识别的Item ID
              dataSource={contrast.map((item) => {
                return { value: item.code, title: item.value };
              })}
              optionTitle={true}
              formItemLayout={FormItemLayout}
              helper={'用以作为对照组，与优化模型的效果进行对比'}
            />
          </Col>
        );
      case 'benchmark':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='业绩比较基准' // 显示名称
              dataIndex='benchmark' // Form识别的Item ID
              dataSource={this.state.benchmarkList}
              rules={[{ required: true, message: '请选择业绩比较基准！' }]}
              optionTitle={true}
              formItemLayout={FormItemLayout}
              disabled={typeStatus == '3'}
            />
          </Col>
        );
      case 'assetConst':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='资产约束' // 显示名称
              dataIndex='assetConst' // Form识别的Item ID
              dataSource={booleanList}
              initialValue='1'
              onChange={(e) => this.props.handleSelectChange(e, 'assetConst')}
              optionTitle={true}
              formItemLayout={FormItemLayout}
              rules={[{ required: true, message: '请选择资产约束！' }]}
              disabled={typeStatus == '3'}
            />
          </Col>
        );
      case 'barraConst':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='Barra因子约束' // 显示名称
              dataIndex='barraConst' // Form识别的Item ID
              dataSource={booleanList}
              initialValue='0'
              onChange={(e) => this.props.handleSelectChange(e, 'barraConst')}
              optionTitle={true}
              formItemLayout={FormItemLayout}
              rules={[{ required: true, message: '请选择Barra因子约束！' }]}
              disabled={typeStatus == '3'}
            />
          </Col>
        );
      case 'groupConst':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='分组约束' // 显示名称
              dataIndex='groupConst' // Form识别的Item ID
              dataSource={booleanList}
              initialValue='1'
              onChange={(e) => this.props.handleSelectChange(e, 'group')}
              optionTitle={true}
              formItemLayout={FormItemLayout}
              rules={[{ required: true, message: '请选择分组约束！' }]}
              disabled={typeStatus == '3'}
            />
          </Col>
        );
      case 'riskfreeRate':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='无风险利率' // 显示名称
              dataIndex='riskfreeRate' // Form识别的Item ID
              dataSource={PORT_OPTIMIZATION_RISK_FREE_RATE.map((item) => {
                return { value: item.code, title: item.value };
              })}
              optionTitle={true}
              formItemLayout={FormItemLayout}
            />
          </Col>
        );
      case 'robust':
        return (
          <Col span={6} key={index}>
            <SelectC
              form={this.props.form} // form对象
              title='Robust优化' // 显示名称
              dataIndex='robust' // Form识别的Item ID
              dataSource={[{ value: '1', title: '否' }]}
              initialValue='1'
              optionTitle={true}
              formItemLayout={FormItemLayout}
              helper={'在优化器无法求解的情况下使用MonteCarlo模拟方法求解'}
              rules={[{ required: true, message: '请选择Robust优化！' }]}
            />
          </Col>
        );
    }
  };
  //组合变更查询 业绩比较基准默认值
  portfolioChange = (e) => {
    if (!e) return;
    this.setState({
      portfolioName: e?.info?.title,
    });
    if (!e?.key) {
      //编辑返回 没有组合id 默认基准下拉
      this.setState({
        benchmarkList: [...benchList],
      });
      return;
    }
    this.props.dispatch({
      type: 'portfolioOptimizationM/queryBenchmarkId',
      payload: {
        portfolioId: e?.key,
      },
      callback: (data) => {
        let arr = data?.value || data?.value == 0 ? [{ ...data }] : [];
        this.setState({
          benchmarkList: arr.concat(benchList),
        });
        this.props.form.setFieldsValue({
          benchmark: data?.value || '0',
        });
      },
    });
  };

  setDataSource = () => {
    let list = [];
    if (this.props.type == '0') {
      list = config.configShock;
    } else if (this.props.type == '1') {
      list = config.bondShock;
    }
    return (
      <div className={'cardBody'}>
        <Form>
          <Row>
            {list.map((item, index) => {
              return this.typeRender(item, index);
            })}
          </Row>
        </Form>
      </div>
    );
  };

  //优化模型切换
  optimizeObjectChange = (e) => {
    // value: "1", title: 'Barra' },{ value: "2", title: '均值-方差'
    //Barra因子约束当选择“Barra”模型时，默认“是”；
    // 当选择“均值-方差”模型时，默认“否”；
    // 当选择“是”时，下方出现【风险因子约束设置】
    this.props.form.setFieldsValue({
      barraConst: e == 1 ? '0' : '1',
    });
    this.props.handleSelectChange(e == 1 ? '0' : '1', 'barraConst');
  };
  //优化目标
  optimizationGoalsChange = (e) => {
    // 当优化目标为“最大化效用”时展示； 风险厌恶系数
    this.setState({
      optimizationGoals: e,
    });
  };

  //重置表单
  reset = () => {
    this.props.form.resetFields();
    this.setState({
      portfolioName: undefined,
    });
  };

  //回填详情
  settingDetails = (data) => {
    this.setState({
      optimizationGoals: data.optimizationGoals,
    });
    this.props.form.setFieldsValue({
      assetConst: `${data.assetConst}`,
      beginDate: moment(data.beginDate),
      benchmark: `${data.benchmark}`,
      contrastConfig: `${data.contrastConfig}`,
      endDate: moment(data.endDate),
      expectReturn: `${data.expectReturn}`,
      expectVolatility: `${data.expectVolatility}`,
      freq: `${data.freq}`,
      groupConst: `${data.groupConst}`,
      optimizeObject: `${data.optimizeObject}`,
      portfolio: `${data.portfolio}`,
      robust: `${data.robust}`,
      riskAversion: data.riskAversion,
      rollBacktest: `${data.rollBacktest}`,
      riskfreeRate: `${data.riskfreeRate}`,
      barraConst: `${data.barraConst}`,
      optimizationGoals: `${data.optimizationGoals}`,
    });
    this.props.handleSelectChange(data.barraConst, 'barraConst');

    this.setState({
      rangedate: [moment(data.beginDate), moment(data.endDate)],
    });
  };

  submit = () => {
    if (this.props.type == '0') {
      this.state.RangeDateC.hasRequired();
    }
    let data;
    this.props.form.validateFields((err, values) => {
      if (err) return;
      data = values;
      data.portfolioName = this.state.portfolioName; //组合名称
    });
    return data;
  };

  render() {
    return <div className='header-search'>{this.setDataSource()}</div>;
  }
}

// props类型
InitFormC.propsTypes = {
  type: PropTypes.string, //0--股票，1--债券，2--基金，3--多资产
  currentModel: PropTypes.number, //优化模型，
  selectCurrent: PropTypes.func, // 切换列表是否下拉表格变化
  handleSelectChange: PropTypes.func, // 优化模型切换
};
export default connect(({ globalM, portfolioOptimizationM }) => ({ globalM, portfolioOptimizationM }))(InitFormC);
